package io.osw.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.osw.common.exception.RRException;
import io.osw.common.utils.PageUtils;
import io.osw.common.utils.R;
import io.osw.common.utils.ValidUtil;
import io.osw.common.validator.ValidatorUtils;
import io.osw.modules.sys.entity.TestUserEntity;
import io.osw.modules.sys.service.TestUserService;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 
 *
 * @author suningxuan
 * @email sunlightcs@gmail.com
 * @date 2018-12-27 14:09:07
 */
@RestController
@RequestMapping("sys/testuser")
public class TestUserController {
    @Autowired
    private TestUserService testUserService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:testuser:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = testUserService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:testuser:info")
    public R info(@PathVariable("id") Integer id) {
        TestUserEntity testUser = testUserService.selectById(id);

        return R.ok().put("testUser", testUser);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:testuser:save")
    public R save(@RequestBody TestUserEntity testUser) {
        testUserService.insert(testUser);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:testuser:update")
    public R update(@RequestBody TestUserEntity testUser) {
        ValidatorUtils.validateEntity(testUser);
        testUserService.updateAllColumnById(testUser);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:testuser:delete")
    public R delete(@RequestBody Integer[] ids) {
        testUserService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        Map<String, Object> msgMap = new HashMap<>();
        List<Map> failMsgList = new ArrayList<>();
        SimpleDateFormat format  = new SimpleDateFormat("yy-MM-dd");
        int successCount = 0;
        try (InputStream ins = file.getInputStream()) {
            Workbook workbook = Workbook.getWorkbook(ins);
            int sheetSize = workbook.getNumberOfSheets();
            for (int i = 0; i < sheetSize; ++i) {
                Sheet sheet = workbook.getSheet(i);
                int rows = sheet.getRows();
                //int columns = sheet.getColumns();
                String phone = "";
                String employeeName = "";
                String address = "";
                String birthday = "";
                //循环取出单元格的内容
                for (int r = 1; r < rows; ++r) {
                    Map<String, String> failMsg = new HashMap<>();
                    try {
                        employeeName = sheet.getCell(0, r).getContents();//姓名
                        phone = sheet.getCell(1, r).getContents(); //手机号码
                        address = sheet.getCell(2, r).getContents(); //地址
                        birthday =sheet.getCell(3, r).getContents(); //生日
                        //数据异常跳过
                        if ((employeeName == null || employeeName.isEmpty()) && (phone == null || phone.isEmpty())) {
                            continue;
                        }
                        if (phone == null || phone.isEmpty()) {
                            failMsg.put("name", employeeName);
                            failMsg.put("phone", phone);
                            failMsg.put("address", address);
                            failMsg.put("birthday", birthday);
                            failMsg.put("msg", "手机号码不能为空");
                            failMsgList.add(failMsg);
                            continue;
                        }
                        if (employeeName == null || employeeName.isEmpty()) {
                            failMsg.put("name", employeeName);
                            failMsg.put("phone", phone);
                            failMsg.put("address", address);
                            failMsg.put("birthday", birthday);
                            failMsg.put("msg", "用户名不能为空");
                            failMsgList.add(failMsg);
                            continue;
                        }
                        if (address == null || address.isEmpty()) {
                            failMsg.put("name", employeeName);
                            failMsg.put("phone", phone);
                            failMsg.put("address", address);
                            failMsg.put("birthday", birthday);
                            failMsg.put("msg", "地址信息不能为空");
                            failMsgList.add(failMsg);
                            continue;
                        }
                        if (birthday == null || birthday.isEmpty()) {
                            failMsg.put("name", employeeName);
                            failMsg.put("phone", phone);
                            failMsg.put("address", address);
                            failMsg.put("birthday", birthday);
                            failMsg.put("msg", "生日不能为空");
                            failMsgList.add(failMsg);
                            continue;
                        }
                        if (!ValidUtil.isMobile(phone)) {
                            failMsg.put("name", employeeName);
                            failMsg.put("phone", phone);
                            failMsg.put("address", address);
                            failMsg.put("birthday", birthday);
                            failMsg.put("msg", "错误的手机号码格式");
                            failMsgList.add(failMsg);
                            continue;
                        }
                        EntityWrapper<TestUserEntity> ew = new EntityWrapper();
                        ew.eq("phone", phone);
                        TestUserEntity testUserEntity = testUserService.selectOne(ew);
                        if (testUserEntity != null) {
                            failMsg.put("name", employeeName);
                            failMsg.put("phone", phone);
                            failMsg.put("address", address);
                            failMsg.put("birthday", birthday);
                            failMsg.put("msg", "用户已存在");
                            failMsgList.add(failMsg);
                            continue;
                        } else {
                            TestUserEntity tue = new TestUserEntity();
                            tue.setPhone(phone);
                            tue.setName(employeeName);
                            tue.setAddress(address);
                            Date bir =format.parse(birthday);
                            tue.setBirthday(bir);
                            testUserService.insert(tue);
                            successCount++;
                        }
                    } catch (Exception e) {
                        failMsg.put("name", employeeName);
                        failMsg.put("phone", phone);
                        failMsg.put("address", address);
                        failMsg.put("birthday", birthday);
                        failMsg.put("msg", "用户添加失败");
                        failMsgList.add(failMsg);
                        continue;
                    }
                }
            }
            msgMap.put("successCount", successCount);
            msgMap.put("failMsgList", failMsgList);
        } catch (Exception e) {
            return R.error("您上传的文件不是合法的Excel2003~2007格式，请检查后缀名是否为.xls");
        }
        return R.ok(msgMap);
    }

    /*
    * 导出数据
    * */
    @RequestMapping(value = "/exportLog", method = RequestMethod.GET)
    public void importExcel(@RequestParam String ids, HttpServletResponse response) throws Exception {
        List list = new ArrayList(Arrays.asList(ids.split("-")));
        StringBuilder sbd = new StringBuilder();
        sbd.append("测试用户数据");
        String title = sbd.toString();
        response.setContentType("application/force-download");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.addHeader("Content-Type", "application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition", new StringBuilder("attachment;filename=").append(URLEncoder.encode(title, "UTF-8")).append(".xlsx").toString());
        try (OutputStream out = response.getOutputStream()) {
            WritableWorkbook workbook = Workbook.createWorkbook(out);
            WritableSheet sheet = workbook.createSheet("测试用户数据", 0);
            //设置列宽
            sheet.setColumnView(0, 20);//名字
            sheet.setColumnView(1, 16);//手机号
            sheet.setColumnView(2, 20);//地址
            sheet.setColumnView(3, 16);//生日
            sheet.getSettings().setVerticalFreeze(1);

            //初始化标题
            WritableFont titleWft = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
            titleWft.setColour(Colour.BROWN);
            WritableCellFormat titleFmt = new WritableCellFormat(titleWft);
            titleFmt.setBackground(Colour.GRAY_25);
            titleFmt.setAlignment(Alignment.CENTRE);
            titleFmt.setVerticalAlignment(VerticalAlignment.CENTRE);
            WritableCellFormat titleFmt1 = new WritableCellFormat();
            titleFmt1.setAlignment(Alignment.LEFT);
            WritableCellFormat titleFmt2 = new WritableCellFormat();
            titleFmt2.setAlignment(Alignment.RIGHT);
            WritableCellFormat priceFmt = new WritableCellFormat(new NumberFormat("#0.00"));

            //写标题
            sheet.addCell(new Label(0, 0, "姓名", titleFmt));
            sheet.addCell(new Label(1, 0, "手机号", titleFmt));
            sheet.addCell(new Label(2, 0, "地址", titleFmt));
            sheet.addCell(new Label(3, 0, "生日", titleFmt));

            SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
            List<TestUserEntity> testUserEntities = testUserService.selectBatchIds(list);
            int row = 1;
            for (TestUserEntity log : testUserEntities) {
                if (StringUtils.isBlank(log.getName()) || log.getName().equals("0")) {
                    sheet.addCell(new Label(0, row, "无", titleFmt1));
                } else {
                    sheet.addCell(new Label(0, row, log.getName()));
                }
                if (StringUtils.isBlank(log.getPhone()) || log.getPhone().equals("0")) {
                    sheet.addCell(new Label(1, row, "无", titleFmt2));
                } else {
                    sheet.addCell(new Label(1, row, log.getPhone()));
                }
                if (StringUtils.isBlank(log.getAddress()) || log.getAddress().equals("0")) {
                    sheet.addCell(new Label(2, row, "无", titleFmt2));
                } else {
                    sheet.addCell(new Label(2, row, log.getAddress()));
                }
                if (log.getBirthday() == null) {
                    sheet.addCell(new Label(3, row, "无", titleFmt2));
                } else {
                    sheet.addCell(new Label(3, row, sdf.format(log.getBirthday())));
                }
                ++row;
            }
            workbook.write();
            workbook.close();
        }
    }

}
